<?php

namespace App\Console\Commands;

use Bouncer;
use DB;
use Illuminate\Console\Command;
use Route;
use Schema;
use Silber\Bouncer\Database\Models;

class Initauth extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'init:auth {--update}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'init auth';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function genPermission()
    {
        foreach (Route::getRoutes() as $route) {
            $routeName = $route->getName();
            if (strpos($routeName, 'notification') !== false) {
                continue;
            }
            if (strpos($routeName, 'api') === false) {
                continue;
            }
            $curPrefix = trim($route->getPrefix(), '/') ?: '';

            if (!$routeName) {
                continue;
            }

            $routePath = $route->uri();
            $title = str_replace('.', ' ', $routeName);

            $desc = config('ability');

            Bouncer::ability()->updateOrCreate([
                'name' => $routeName,
            ], ['title' => isset($desc[$routeName]) ? $desc[$routeName] : $title]);
        }
    }

    public function up()
    {

    }
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $isUpdate = $this->option('update');
        if ($isUpdate) {
            $this->genPermission();
            $this->line('update finish !!!');
            return;
        }
        // $this->up();
        Schema::disableForeignKeyConstraints();
        DB::transaction(function () {
            DB::statement('truncate table abilities;');
            DB::statement('truncate table assigned_roles');
            DB::statement('truncate table permissions');
            DB::statement('truncate table roles');
            if (!Schema::hasColumn('abilities', 'route_path')) {
                DB::statement('alter table abilities add column route_path varchar(150) default null after `name`');
            }
        });

        $time = date('Y-m-d H:i:s');
        $data = [
            ['name' => 'superadmin', 'title' => '超级管理员', 'level' => null, 'scope' => null, 'created_at' => $time, 'updated_at' => $time],
            ['name' => 'company_admin', 'title' => '管理员', 'level' => null, 'scope' => null, 'created_at' => $time, 'updated_at' => $time],
            ['name' => 'member', 'title' => '普通用户', 'level' => null, 'scope' => null, 'created_at' => $time, 'updated_at' => $time],
        ];
        DB::table('roles')->insert($data);

        $user = \App\Models\SyUser::find(126);

        Bouncer::assign('superadmin')->to($user);

        $member = \App\Models\SyUser::find(166);

        $defaultRole = 'member';

        Bouncer::assign($defaultRole)->to($member);

        $abilities = [
            'api.auth.login',
            'api.auth.logout',
            'api.auth.refresh',
            'api.auth.getUserInfo',
            'api.auth.saveUserInfo',
            'api.auth.modifyPassword',
            'api.auth.forgetpassword',
            'api.auth.sendcode',
            'api.upload.store',
            'api.userlog.index',
        ];
        // Bouncer::allow($user)->toOwnEverything();
        $this->genPermission();
        // Bouncer::assign($defaultRole)->to($user);
        Bouncer::sync($defaultRole)->abilities($abilities);
        Schema::enableForeignKeyConstraints();
    }
}
